/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * StudentMain.java
 *
 * Created on 2011-10-24, 16:06:15
 */
package com.edu.kamai.client;

import com.edu.kamai.client.control.contestControl;
import com.edu.kamai.client.control.paperAnswerControl;
import com.edu.kamai.client.control.paperControl;
import com.edu.kamai.client.control.scoreControl;
import com.edu.kamai.client.download.fileDownload;
import com.edu.kamai.config.Constant;
import com.edu.kamai.utility.FileName;
import com.edu.kamai.webservice.contest.Contest;
import com.edu.kamai.webservice.paper.Paper;
import com.edu.kamai.webservice.paperanswer.PaperAnswer;
import com.edu.kamai.webservice.score.Score;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author xyzhu
 */
public class StudentMain extends javax.swing.JFrame {

    /** Creates new form StudentMain */
    public StudentMain(String sn) {
        initComponents();
        setNet();
        sutdentName = sn;
    }
    
    private void showMessage(int ans,String msg){
        if(ans == 1){
            javax.swing.JOptionPane.showMessageDialog(this, msg, "Done", ans);
        }else{
            javax.swing.JOptionPane.showMessageDialog(this, msg, "Error", ans);
        }
    }
    
    private void setNet(){
        try{
            InputStream in = getClass().getResourceAsStream(Constant.netiniFilePath);
            Scanner scan = new Scanner(in);
            List<String> netList = new ArrayList<String>();
            
            while(scan.hasNextLine()){
                String line = scan.nextLine();
                if(!line.equals("")){
                    if(!line.startsWith("#")){
                        netList.add(line);
                    }
                }
            }
            paperAnswerControl.setNetList(netList);
            paperControl.setNetList(netList);
            contestControl.setNetList(netList);
            scoreControl.setNetList(netList);
            scan.close();
            in.close();
        }catch(Exception ex){
            ex.printStackTrace();
            //Control.setNetList(new ArrayList<String>());
        }
        paperControl.setServer();
        contestControl.setServer();
        scoreControl.setServer();
        paperAnswerControl.setServer();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        Bdownload = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TA_Contest = new javax.swing.JTable();
        B_ShowContest = new javax.swing.JButton();
        B_downloadAndBegin = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        TA_Score = new javax.swing.JTable();
        B_Score = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        TA_Contest.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        TA_Contest.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TA_ContestMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TA_Contest);

        B_ShowContest.setText("Show Contest");
        B_ShowContest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_ShowContestActionPerformed(evt);
            }
        });

        B_downloadAndBegin.setText("Begin");
        B_downloadAndBegin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_downloadAndBeginActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout BdownloadLayout = new javax.swing.GroupLayout(Bdownload);
        Bdownload.setLayout(BdownloadLayout);
        BdownloadLayout.setHorizontalGroup(
            BdownloadLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(BdownloadLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 440, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(39, 39, 39)
                .addGroup(BdownloadLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(B_downloadAndBegin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(B_ShowContest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(47, Short.MAX_VALUE))
        );
        BdownloadLayout.setVerticalGroup(
            BdownloadLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE)
            .addGroup(BdownloadLayout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(B_ShowContest)
                .addGap(18, 18, 18)
                .addComponent(B_downloadAndBegin)
                .addContainerGap(362, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Contest", Bdownload);

        TA_Score.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        TA_Score.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TA_ScoreMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(TA_Score);

        B_Score.setText("My Score");
        B_Score.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                B_ScoreActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 462, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(41, 41, 41)
                .addComponent(B_Score)
                .addContainerGap(47, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(B_Score)
                .addContainerGap(405, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Score", jPanel2);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 631, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 448, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("tab3", jPanel3);

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 477, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void B_ShowContestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_ShowContestActionPerformed
        // TODO add your handling code here:
        List<Contest> contest = null;
        contest = contestControl.findContest();
        myDefaultTableModel model = new myDefaultTableModel();
        TA_Contest.setModel(model);
        model.addColumn("Contest ID");
        model.addColumn("Contest Title");
        model.addColumn("Contest Description");
       
        for(int i=0;i<contest.size();i++){
            Contest tmp = contest.get(i);
            String cID = tmp.getContestId().toString();
            String cTitle = tmp.getTitle();
            String cDesc = tmp.getDescription();
            model.insertRow(i, new Object[]{cID,cTitle,cDesc});
        }
    }//GEN-LAST:event_B_ShowContestActionPerformed

    private void downloadPaper(int roleID,int pid){
        if(pid == -1){
            papers.put(roleID, null);
            showMessage(0, "no " + Constant.paperRoleTable[roleID] + " paper");
        }else{
            String url = Constant.urlAddress + "kamai_edu";
            Paper paper = paperControl.findPaperByIDAndRole(roleID, pid);
            String paperPath  = paper.getPaperPath();
            url = url + paperPath;
            
            int pos = paperPath.lastIndexOf("/") + 1;
            String filename = FileName.getDefaultKamaiFolder() + paperPath.substring(pos);
            fileDownload fd = new fileDownload(url, filename);
            fd.start();
            papers.put(roleID, filename);
        }
        papersID.put(roleID,pid);
    }
    
    private void B_downloadAndBeginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_downloadAndBeginActionPerformed
        // TODO add your handling code here:
        /*
        papers = new HashMap<Integer, String>();
        papersID = new HashMap<Integer, Integer>();
        int selectContestRow = TA_Contest.getSelectedRow();
        int contestID = Integer.parseInt(TA_Contest.getValueAt
                (selectContestRow, 0).toString());
        Contest contest = contestControl.findContestByID(contestID);
        paperTitle = contest.getTitle();
        if(paperTitle == null){
            paperTitle = "";
        }
        
        int rid = contest.getReadingId();
        downloadPaper(Constant.READING_PAPER_ID, rid);
        int lid = contest.getListeningId();
        downloadPaper(Constant.LISTENING_PAPER_ID, lid);
        int wid = contest.getWritingId();
        downloadPaper(Constant.WRITING_PAPER_ID, wid);
        int sid = contest.getSpeakingId();
        downloadPaper(Constant.SPEAKING_PAPER_ID, sid);
        
        new ContestFrm(sutdentName,papers,papersID,paperTitle,contestID,this).
                setVisible(true);
        this.setVisible(false);
        */
    }//GEN-LAST:event_B_downloadAndBeginActionPerformed

    private void TA_ContestMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TA_ContestMouseClicked
        // TODO add your handling code here:
        if(evt.getClickCount() == 2){
            papers = new HashMap<Integer, String>();
            papersID = new HashMap<Integer, Integer>();
            int selectContestRow = TA_Contest.getSelectedRow();
            int contestID = Integer.parseInt(TA_Contest.getValueAt
                    (selectContestRow, 0).toString());
            Contest contest = contestControl.findContestByID(contestID);
            paperTitle = contest.getTitle();
            if(paperTitle == null){
                paperTitle = "";
            }

            int rid = contest.getReadingId();
            downloadPaper(Constant.READING_PAPER_ID, rid);
            int lid = contest.getListeningId();
            downloadPaper(Constant.LISTENING_PAPER_ID, lid);
            int wid = contest.getWritingId();
            downloadPaper(Constant.WRITING_PAPER_ID, wid);
            int sid = contest.getSpeakingId();
            downloadPaper(Constant.SPEAKING_PAPER_ID, sid);

            new ContestFrm(sutdentName,papers,papersID,paperTitle,contestID,this).
                    setVisible(true);
            this.setVisible(false);
        }
    }//GEN-LAST:event_TA_ContestMouseClicked

    private void B_ScoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_ScoreActionPerformed
        // TODO add your handling code here:
        myDefaultTableModel model = new myDefaultTableModel();
        TA_Score.setModel(model);
                
        studentScore = scoreControl.getScoreByUserID(sutdentName);
        
        model.addColumn("Contest ID");
        model.addColumn("Student");
        model.addColumn("Score");
        
        for(int i = 0;i < studentScore.size();i++){
            Score tmp = studentScore.get(i);
            String contestID = Integer.toString(tmp.getContestId());
            String scroe = Integer.toString(tmp.getScore());
            model.insertRow(i, new Object[]{contestID,sutdentName,scroe});            
        }
        
    }//GEN-LAST:event_B_ScoreActionPerformed

    private void showContestDetail(int selectRow){
        Score tmp = studentScore.get(selectRow);
        int cid = tmp.getContestId();
        List<PaperAnswer> res = paperAnswerControl.
                getAnswerScoreByContestIDAndUserID(cid, sutdentName);
        String scoreString = "";
        int total = 0;
        for(int i=0;i<res.size();i++){
            PaperAnswer pa = res.get(i);
            int role = pa.getPaperRole();
            String paperrole = Constant.paperRoleTable[role];
            int score = pa.getScore();
            total += score;
            scoreString += paperrole + " : " + score + "\n";
        }
        
        scoreString += "Total : " + total;
        showMessage(1, scoreString);
    }
    
    private void TA_ScoreMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TA_ScoreMouseClicked
        // TODO add your handling code here:
        if(2 == evt.getClickCount()){
            int selectedRow = TA_Score.getSelectedRow();
            showContestDetail(selectedRow);
        }
    }//GEN-LAST:event_TA_ScoreMouseClicked

    /**
     * @param args the command line arguments
     */
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new StudentMain("test").setVisible(true);
            }
        });
    }
    
    private List<Score> studentScore;
    private String sutdentName;
    private String paperTitle;
    private HashMap<Integer,String> papers;
    private HashMap<Integer,Integer> papersID;
       
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton B_Score;
    private javax.swing.JButton B_ShowContest;
    private javax.swing.JButton B_downloadAndBegin;
    private javax.swing.JPanel Bdownload;
    private javax.swing.JTable TA_Contest;
    private javax.swing.JTable TA_Score;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    // End of variables declaration//GEN-END:variables
}
